# Importing Data
TAIWAN <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/UAE/Taiwan.xlsx")

# Checking the Imported Data
View(TAIWAN)

# Creating Time Series Data
TAIWAN_ts <- ts(TAIWAN, start=c(2002,01), end=c(2019,06), frequency=12)

# Viewing and Checking the Created Time Series Data
TAIWAN_ts
sum(is.na(TAIWAN_ts))
library(forecast)
TAIWAN_ts <- tsclean(TAIWAN_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(TAIWAN_ts)
plot(aggregate(TAIWAN_ts,FUN=mean))

# Decomposing
TAIWAN_ts_decomp <- decompose(TAIWAN_ts)
plot(TAIWAN_ts_decomp)

# Testing for Stationarity
acf(TAIWAN_ts, lag.max=20)
pacf(TAIWAN_ts, lag.max=20)

# To see any seasonal effect
boxplot(TAIWAN_ts~cycle(TAIWAN_ts))

# To remove trend effect
TAIWAN_ts_diff <- diff(TAIWAN_ts)
plot(TAIWAN_ts_diff)

# To remove variance effect
TAIWAN_ts_log <- log(TAIWAN_ts)
plot(TAIWAN_ts_log)

# To remove both (Trend and Variance) effects
TAIWAN_ts_both <- diff(log(TAIWAN_ts))
plot(TAIWAN_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(TAIWAN_ts, lag.max=20)
acf(log(TAIWAN_ts), lag.max=20)
acf(diff(TAIWAN_ts), lag.max=20)
acf(diff(log(TAIWAN_ts)), lag.max=20)
pacf(TAIWAN_ts, lag.max=20)
pacf(log(TAIWAN_ts), lag.max=20)
pacf(diff(TAIWAN_ts), lag.max=20)
pacf(diff(log(TAIWAN_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
TAIWAN_ts_model <- auto.arima(TAIWAN_ts)
TAIWAN_ts_model
TAIWAN_ts_model <- auto.arima(TAIWAN_ts, ic="aic", trace = TRUE)
TAIWAN_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(TAIWAN_ts_model$resid)
acf(TAIWAN_ts_model$residuals, main='ACF Residual')
pacf(TAIWAN_ts_model$residuals, main='ACF Residual')
Box.test(TAIWAN_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
TAIWAN_ts_forecast <- forecast (TAIWAN_ts_model, level=c(95), h=258)
plot(TAIWAN_ts_forecast)
TAIWAN_ts_forecast             


write.table(TAIWAN_ts_forecast, file="Taiwan_TSA.csv", sep=",")
